package com.gucheng.springframework.beans.factory.support;

import com.gucheng.springframework.beans.BeansException;
import com.gucheng.springframework.beans.factory.config.BeanDefinition;


import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    //使用CGLIB库创建bean实例
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();


    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition, beanName, args);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        addSingleton(beanName, bean);
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        Constructor constructorToUse = null;
        //1.通过Bean定义(beanDefinition)获取Bean的类信息
        Class<?> beanClass = beanDefinition.getBeanClass();
        //2.获取这个类的所有构造函数
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        //3.遍历bean定义中的所有构造函数，找到一个匹配的构造函数
        for (Constructor ctor : declaredConstructors) {
            //构造函数的参数类型数量要与传入的参数（args）数量相同
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }
        //创建bean实例
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

}
